package com.zc.mychart.model;

import com.github.mikephil.charting.data.CandleEntry;
import com.github.mikephil.charting.data.Entry;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/2/27 0027.
 */

public class BOLLEntrys {
    private List<Entry> UPs;
    private List<Entry> MBs;
    private List<Entry> DNs;
    private final int N = 20;

    /**
     * （1）计算MA
     * MA=N日内的收盘价之和÷N
     * （2）计算标准差MD
     * MD=平方根N日的（C－MA）的两次方之和除以N
     * （3）计算MB、UP、DN线
     * MB=（N－1）日的MA
     * UP=MB+k×MD
     * DN=MB－k×MD
     * （K为参数，可根据股票的特性来做相应的调整，一般默认为2）
     *
     * @param list
     */
    public BOLLEntrys(List<CandleEntry> list) {
        UPs = new ArrayList<>();
        MBs = new ArrayList<>();
        DNs = new ArrayList<>();

        float ma, md, mb, up, dn, x;

        if (list != null && list.size() > 0) {
            float closeSum;
            float sum;
            for (int i = N - 1; i < list.size(); i++) {
                closeSum = getSumClose(i, list);
                ma = closeSum / N;
                sum = getSum(i, ma, list);
                md = (float) Math.sqrt(sum / N);
                mb = (closeSum - list.get(i).getClose()) / (N - 1);
                up = mb + (2 * md);
                dn = mb - (2 * md);
                x = list.get(i).getX();
                UPs.add(new Entry(x, up));
                MBs.add(new Entry(x, mb));
                DNs.add(new Entry(x, dn));
            }
        }
    }

    private float getSum(int end, float ma, List<CandleEntry> list) {
        CandleEntry candleEntry;
        float sum = 0.0f;
        for (int j = 0; j < N; j++) {
            candleEntry = list.get(end - j);
            sum += ((candleEntry.getClose() - ma) * (candleEntry.getClose() - ma));
        }
        return sum;
    }

    private float getSumClose(int end, List<CandleEntry> list) {
        float close = 0.0f;
        for (int j = 0; j < N; j++) {
            close += list.get(end - j).getClose();
        }
        return close;
    }

    public List<Entry> getUPs() {
        return UPs;
    }

    public List<Entry> getMBs() {
        return MBs;
    }

    public List<Entry> getDNs() {
        return DNs;
    }
}
